package ink.xiaobaibai.controller.onePay;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ink.xiaobaibai.annotation.InsidePublicResources;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.common.SelectOrderBo;
import ink.xiaobaibai.common.SelectOrderBo2;
import ink.xiaobaibai.entity.AdminUser;
import ink.xiaobaibai.entity.ClientOrder;
import ink.xiaobaibai.entity.OzoneDevice;
import ink.xiaobaibai.entity.OzonePrice;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IClientOrderService;
import ink.xiaobaibai.service.IOzoneDeviceService;
import ink.xiaobaibai.service.IOzonePriceService;
import ink.xiaobaibai.units.MySecurity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @description: 订单查看
 * @author: 小白白
 * @create: 2021-05-25
 **/

@Api(tags = "订单接口")
@RequestMapping("/onePay/order")
@CrossOrigin
@RestController
@InsidePublicResources
public class OrderController {

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private IOzoneDeviceService ozoneDeviceService;

    @Autowired
    private IClientOrderService clientOrderService;

    @Autowired
    private IOzonePriceService priceService;

    /**
     * 查看所有订单
     */
    @PostMapping("/list")
    @ApiOperation("查看所有订单 管理员专属")
    @ResourcesRoleMapping(resourceName = "查看所有订单", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_ONE})
    public ResponseFormat list(@RequestBody @Validated SelectOrderBo2 selectOrderBo2) {
        QueryWrapper<ClientOrder> q1 = new QueryWrapper<>();
        if (selectOrderBo2.getAdminUserId() != null) {
            q1.eq("admin_user_id", selectOrderBo2.getAdminUserId());
        }
        if (selectOrderBo2.getDepId() != null) {
            q1.eq("admin_dep_id", selectOrderBo2.getDepId());
        }
        if (selectOrderBo2.getDeviceId() != null) {
            q1.eq("device_id", selectOrderBo2.getDeviceId());
        }
        if (selectOrderBo2.getStartTime() != null && selectOrderBo2.getEndTime() != null) {
            q1.between("create_time", selectOrderBo2.getStartTime(), selectOrderBo2.getEndTime());
        }
        q1.orderByDesc("create_time");
        Page<ClientOrder> page = this.clientOrderService.page(new Page<>(selectOrderBo2.getPageNum(), selectOrderBo2.getPageSize()), q1);
        return ResponseFormat.success(page);
    }

    /**
     * 查看个人订单
     * 查询条件:  时间段 单次 订单id 机器id
     * 返回信息:  订单id  订单金额 机器id(可点击) 创建时间
     */
    @PostMapping("/list/user/{userId}")
    @ApiOperation("查看个人订单")
    public ResponseFormat getOrderListByUserId(@PathVariable("userId") Integer userId,
                                               @RequestBody @Validated SelectOrderBo selectOrderBo) {
        Integer authenticationUserId = MySecurity.getUserId();
        if (!MySecurity.isPower(MyRole.POWER_ONE)) {
            String role = MySecurity.getRole();
            /**
             * 个人身份验证->个人只能看自己的订单列表
             */
            if (role.equals(MyRole.DISTRIBUTOR) && !userId.equals(authenticationUserId)) {
                return ResponseFormat.fail("权限不足");
            }
            /**
             * 经理身份验证->经理只能查看自己部门的订单列表
             */
            if (role.equals(MyRole.AGENT) && !this.adminUserService.identicalDep(userId, authenticationUserId)) {
                return ResponseFormat.fail("不可查看其他部门人员");
            }
        }
        //通过验证
        QueryWrapper<ClientOrder> q1 = this.createClientOrderQueryWrapper(selectOrderBo);
        q1.eq("admin_user_id", userId);
        Page<ClientOrder> page = this.clientOrderService.page(new Page<>(selectOrderBo.getPageNum(), selectOrderBo.getPageSize()), q1);
        return ResponseFormat.success(page);
    }

    /**
     * 查看部门的订单
     */
    @PostMapping("/list/department/{id}")
    @ApiOperation("查看部门的单次订单")
    public ResponseFormat getOrderListByDepartment(@PathVariable("id") Integer depId,
                                                   @RequestBody @Validated SelectOrderBo selectOrderBo) {
        Integer authenticationUserId = MySecurity.getUserId();
        if (!MySecurity.isPower(MyRole.POWER_ONE)) {
            String role = MySecurity.getRole();
            if (role.equals(MyRole.DISTRIBUTOR)) {
                //业务员无权查看
                return ResponseFormat.fail("无权限");
            }
            if (role.equals(MyRole.AGENT)) {
                //经理只能查看当前自己部门的订单
                QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
                q1.select("department_id");
                q1.eq("id", authenticationUserId);
                AdminUser adminUser = this.adminUserService.getOne(q1);
                if (!adminUser.getDepartmentId().equals(depId)) {
                    return ResponseFormat.fail("不可查询其他部门订单");
                }
            }
        }
        //通过验证
        QueryWrapper<ClientOrder> q1 = this.createClientOrderQueryWrapper(selectOrderBo);
        q1.eq("admin_dep_id", depId);
        Page<ClientOrder> page = this.clientOrderService.page(new Page<>(selectOrderBo.getPageNum(), selectOrderBo.getPageSize()), q1);
        return ResponseFormat.success(page);
    }

    /**
     * 根据臭氧机器查看订单
     */
    @PostMapping("/list/ozoneDevice/{id}")
    @ApiOperation("根据臭氧机器查看订单|禁止同时传入机器id和机器识别码")
    public ResponseFormat getOrderListByOzoneDeviceId(@PathVariable("id") Integer deviceId,
                                                      @RequestBody @Validated SelectOrderBo selectOrderBo) {
        Integer authenticationUserId = MySecurity.getUserId();
        if (!MySecurity.isPower(MyRole.POWER_ONE)) {
            String role = MySecurity.getRole();
            if (role.equals(MyRole.DISTRIBUTOR)) {
                QueryWrapper<OzoneDevice> q1 = new QueryWrapper<>();
                q1.eq("id", deviceId);
                q1.eq("admin_user_id", authenticationUserId);
                if (this.ozoneDeviceService.count(q1) == 0) {
                    //业务员只能查看自己的负责的机器
                    return ResponseFormat.fail("只能查看自己的机器");
                }
            }
            if (role.equals(MyRole.AGENT) && !this.ozoneDeviceService.identicalDeviceDepByUserId(authenticationUserId, deviceId)) {
                //经理只能查看自己部门负责的机器
                return ResponseFormat.fail("只能查看自己部门的机器");
            }
        }
        //通过校验
        QueryWrapper<ClientOrder> q1 = this.createClientOrderQueryWrapper(selectOrderBo);
        q1.eq("device_id", deviceId);
        Page<ClientOrder> page = this.clientOrderService.page(new Page<>(selectOrderBo.getPageNum(), selectOrderBo.getPageSize()), q1);
        return ResponseFormat.success(page);
    }

    @GetMapping("/item")
    @ApiOperation("查看单次支付订单详细")
    public ResponseFormat getOrderItem(@RequestParam("orderId") String orderId) {
        // 订单信息
        ClientOrder clientOrder = this.clientOrderService.getById(orderId);
        // 机器信息
        QueryWrapper<OzoneDevice> q1 = new QueryWrapper<>();
        q1.select("id", "device_code", "admin_user_id", "price_id", "address", "province_city");
        q1.eq("id", clientOrder.getDeviceId());
        OzoneDevice ozoneDevice = this.ozoneDeviceService.getOne(q1);
        if (ozoneDevice == null) {
            return ResponseFormat.fail("当前机器不存在");
        }
        // 价格时间段
        OzonePrice ozonePrice = this.priceService.getById(ozoneDevice.getPriceId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("order", clientOrder);
        jsonObject.put("device", ozoneDevice);
        jsonObject.put("price", ozonePrice);
        return ResponseFormat.success(jsonObject);
    }

    @GetMapping("/listByClientId")
    @ApiOperation("根据用户Id查看订单")
    public ResponseFormat getListByClientId(@RequestParam("clientId") Integer clientId,
                                            @RequestParam("pageNum") Integer pageNum,
                                            @RequestParam("pageSize") Integer pageSize) {
        IPage<ClientOrder> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ClientOrder> q1 = new QueryWrapper<>();
        q1.eq("user_id", clientId);
        IPage<ClientOrder> result = this.clientOrderService.page(page, q1);
        return ResponseFormat.success(result);
    }

    /**
     * 查询方法
     */
    private QueryWrapper<ClientOrder> createClientOrderQueryWrapper(SelectOrderBo selectOrderBo) {
        QueryWrapper<ClientOrder> q1 = new QueryWrapper<>();
        if (selectOrderBo.getDeviceId() != null) {
            //机器id
            q1.eq("device_id", selectOrderBo.getDeviceId());
        }
        if (selectOrderBo.getDeviceCode() != null) {
            //识别码
            QueryWrapper<OzoneDevice> q2 = new QueryWrapper<>();
            q2.select("id");
            q2.eq("device_code", selectOrderBo.getDeviceCode());
            OzoneDevice ozoneDevice = this.ozoneDeviceService.getOne(q2);
            if (ozoneDevice != null) {
                //机器码优先
                q1.eq("device_id", ozoneDevice.getId());
            }
        }
        if (selectOrderBo.getStartTime() != null && selectOrderBo.getEndTime() != null) {
            //时间段
            q1.between("create_time", selectOrderBo.getStartTime(), selectOrderBo.getEndTime());
            q1.orderByAsc("create_time");
        } else {
            q1.orderByDesc("create_time");
        }
        if (selectOrderBo.getOrderId() != null) {
            //订单id
            q1.eq("order_id", selectOrderBo.getOrderId());
        }
        return q1;
    }

}
